package WebHard;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.lang.reflect.Array;
import java.util.ArrayList;
import WebHard.User;

/**
 * Created by RaysMac on 14. 12. 15..
 */
@WebServlet(name = "Servlet_login")
public class Servlet_login extends HttpServlet {
    public static String path;
    public static String root;
    public static ArrayList<File> filelist=new ArrayList<File>();
    public static User me;
    static File dir;
    static ArrayList <User> userlist;

    public void init() throws ServletException {
        //String dirName=this.getInitParameter()
        ServletContext context=this.getServletContext();
        path=context.getRealPath("/");

        dir=new File(path,"users");
        if(!dir.exists()){
            dir.mkdir();
        }
        userlist = new ArrayList <User>();


        File file=new File(dir,"user");


        try {
            if (file.exists()) {
                FileReader fr = new FileReader(file);
                BufferedReader br = new BufferedReader(fr);
                String data;

                while (((data = br.readLine()) != null)) {
                    userlist.add(new User(data.substring(0, data.indexOf(" ")), data.substring(data.indexOf(" ") + 1, data.length())));

                }
                br.close();
                fr.close();
            } else {
                FileWriter fw = new FileWriter(file);
                fw.write("");
                fw.close();
            }
        }
        catch(Exception e)
        {

        }

    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=utf-8");
        String uri=request.getRequestURI();
        String id=request.getParameter("id");
        String pwd=request.getParameter("pwd");



        User user1 =new User(id,pwd);

        /*File dir=new File(path,"users");
        if(!dir.exists()){
            dir.mkdir();
        }
        init부분에서 실행해 줘서 삭제.
        */
        File file=new File(dir,"user");

        if (file.exists()) {
            FileReader fr=new FileReader(file);
            BufferedReader br= new BufferedReader(fr);
            String data;

            while (((data = br.readLine()) != null)) {
                userlist.add(new User(data.substring(0, data.indexOf(" ")), data.substring(data.indexOf(" ")+1, data.length())));

            }
            br.close();
            fr.close();
        }
        else
        {
            FileWriter fw=new FileWriter(file);
            fw.write("");
            fw.close();
        }


        if(uri.equals("/user/logout")){
            request.getSession().invalidate();
            response.sendRedirect("/index.jsp");

        }
        if(uri.equals("/user/login")){

            if(id == null || pwd==null || id.length() ==0 || pwd.length()==0){
                PrintWriter out = response.getWriter();
                out.println("<html><body>");
                out.println("<script type=\"text/javascript\">");
                out.println("var popwin = window.open('/pop.jsp','이동합니다','width=300, height=5, menubar=no, status=no, toolbar=no location=no resizable=no')");
                out.println("setTimeout(function(){ popwin.close(); window.location.href='/index.jsp';},2000)");
                out.println("</script>");
                out.println("</body></html>");
                //response.sendRedirect("/index.jsp");
                return;
            }

            response.getWriter().print("로그인 서블릿 ");
            //userlist.get(0).toString();
            for(User user2 : userlist)
            {
                if(user1.id.equals(user2.id) && user1.pwd.equals(user2.pwd))
                {
                    response.getWriter().print("로그인 성공");
                    root=path+"/users/"+user1.id;
                    if(request.getParameter("autologin")!=null)
                    {
                        request.getSession().setAttribute("loginid",user1.id);
                    }
                    me=user1;
                    response.sendRedirect("/me/");
                    break;

                }
            }

            response.getWriter().println("로그인 실패\t<a href=\"/index.jsp\">로그인 페이지로 이동 </a>");

        }

        else if(uri.equals("/user/join")){
            boolean sucess=true;
            response.getWriter().print("회원가입 서블릿<br/>");
            FileWriter fw=new FileWriter(file,true);
            BufferedWriter bw = new BufferedWriter(fw);
            for(User user2 : userlist)
            {
                response.getWriter().println(user1.id+" "+user2.id+"<br/>");
                if(user1.id.equals(user2.id))
                {
                    response.getWriter().print("아이디가 중복 실패");
                    sucess=false;
                    break;
                }
            }
            if(sucess)
            {
                bw.write(user1.toString() + "\n");
                bw.close();
                fw.close();
                userlist.add(user1);
                File file1=new File(path+"/users/",user1.id);
                if(!file1.exists())
                    file1.mkdir();
                response.getWriter().print("회원가입에 성공하였습니다.\t<a href=\"/index.jsp\">로그인 페이지로 이동 </a>");
                //    response.getWriter().print(path);
            }
            else
            {
                response.getWriter().print("아이디가 중복됩니다.\t<a href=\"/join.jsp\">회원가입 페이지로 이동</a>");
            }
        }

        if(uri.equals("/user/mkdir"))
        {
         String dirname=request.getParameter("fldrname");
            String nowpath=request.getParameter("nowdir");
            response.getWriter().print(nowpath+" "+dirname);
            File newdir=new File(nowpath,dirname);
            if(!newdir.exists())
            {
                newdir.mkdir();

            }
            response.sendRedirect("/me/");
        }

        if(uri.equals("/user/deldir"))
        {
            String delname=request.getParameter("delforder");
            String nowpath=request.getParameter("nowdir");
            response.getWriter().print(delname);


            //String nowpath=request.getParameter("nowdir");
            File deldir = new File(nowpath,delname);
            deldir.delete();
            response.sendRedirect("/me/");

        }



    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=utf-8");
        response.sendRedirect("/index.jsp");



    }

    static void makepop(HttpServletResponse response) throws IOException {
        PrintWriter out = response.getWriter();
        out.println("<html><body>");
        out.println("<script type=\"text/javascript\">");
        out.println("var popwin = window.open('/pop.jsp','이동합니다','width=300, height=5, menubar=no, status=no, toolbar=no location=no resizable=no')");
        out.println("setTimeout(function(){ popwin.close(); window.location.href='/index.jsp';},2000)");
        out.println("</script>");
        out.println("</body></html>");
    }

}
